package com.bauer.springboot.starter.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;

import com.bauer.springboot.starter.props.XXLJobProperties;
import com.xxl.job.core.executor.XxlJobExecutor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description:
 * @author: weirui
 * @create: 2020-01-14 15:58
 **/
@Configuration
@EnableConfigurationProperties(XXLJobProperties.class)
@ConditionalOnClass(value = {XxlJobExecutor.class})
public class XXLJobAutoConfiguration {

    private static Logger logger = LoggerFactory.getLogger(XXLJobAutoConfiguration.class);

    private XXLJobProperties xxlJobProperties;

    public XXLJobAutoConfiguration(XXLJobProperties xxlJobProperties) {
        this.xxlJobProperties = xxlJobProperties;
    }

    /**
     * 当存在 xxl.job.admin.address时才会自动创建bean
     */
    @Bean(initMethod = "start", destroyMethod = "destroy")
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "xxl.job.admin", value = "addresses")
    public XxlJobExecutor getXxlJobExecutor() {
        XxlJobExecutor xxlJobExecutor = new XxlJobExecutor();
        xxlJobExecutor.setAdminAddresses(xxlJobProperties.getAdmin().getAddresses());
        xxlJobExecutor.setAppName(xxlJobProperties.getExecutor().getAppname());
        xxlJobExecutor.setIp(xxlJobProperties.getExecutor().getIp());
        xxlJobExecutor.setPort(xxlJobProperties.getExecutor().getPort());
        xxlJobExecutor.setAccessToken(xxlJobProperties.getAccessToken());
        xxlJobExecutor.setLogPath(xxlJobProperties.getExecutor().getLogpath());
        xxlJobExecutor.setLogRetentionDays(xxlJobProperties.getExecutor().getLogRetentionDays());
        logger.info("XxlJobExecutor init success");
        return xxlJobExecutor;
    }

}
